//
//  ProfileHost.swift
//  codelabs
//
//  Created by 雷雷 on 24/05/2025.
//

import SwiftUI

struct ProfileHost: View {
    @Environment(ModelData.self) var modelData
    @Environment(\.editMode) var editMode
    @State var draftProfile:Profile = Profile.default
    
    var body: some View {
        
        ScrollView(.vertical,showsIndicators: false){
            VStack(alignment:.leading){
                
                HStack{
                    if editMode?.wrappedValue == .active{
                        Button("Cancel",role: .cancel){
                            draftProfile=modelData.profile
                            editMode?.animation().wrappedValue = .inactive
                        }
                    }
                    Spacer()
                    EditButton()
                }
                
                
                if editMode?.wrappedValue == .inactive {
                    // Summary
                    ProfileSummary(profile: modelData.profile)
                    
                    Divider()
                    
                    
                    // Badges
                    VStack(alignment:.leading){
                        Text("Completed Badges")
                            .font(.headline)
                            .bold()
                        
                        ScrollView(.horizontal){
                            
                            HStack{
                                HikeBadge(name:"First Hike")
                                
                                HikeBadge(name:"Earth Day")
                                    .hueRotation(Angle(degrees: 90))
                                
                                
                                HikeBadge(name:"Tenth Hike")
                                    .grayscale(0.5)
                                    .hueRotation(Angle(degrees: 45))
                                
                            }.padding(.bottom)
                            
                        }
                    }
                    
                    Divider()
                    
                    // Chart
                    VStack(alignment:.leading){
                        Text("Recent Hikes")
                            .font(.headline)
                            .bold()
                        
                        
                        HikeView(hike:modelData.hikes[0])
                    }
                    
                }else{
                    ProfileEditor(profile: $draftProfile)
                        .onAppear{
                            draftProfile=modelData.profile
                        }
                        .onDisappear{
                            modelData.profile=draftProfile
                        }
                }
                
            }
            .padding()
        }
    }
    
}

#Preview {
    ProfileHost()
        .environment(ModelData())
}
